import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
from skimage import io
from skimage import transform
from my.common.public import *

DEFAULT_TYPE = "bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,JPEG,dxf,ufo,eps,ai,raw,WMF"
deType = DEFAULT_TYPE.split(',')


def wAllImgToCsv(imgDir, tag, toCsv, output_shape=(100, 100)):
    '''
    把目录中的图片按照标签分类,并且写入到csv中(第一位为 标签,后面的为 特征)
    :param imgDir:
    :param tag:
    :param toCsv:
    :param output_shape:
    :return:
    '''
    # wAllImgToCsv(r'G:\xampp\htdocs\my\python\imgClassify\manDir', 1, r'G:\xampp\htdocs\my\python\imgClassify\manWoman.csv')
    # wAllImgToCsv(r'G:\xampp\htdocs\my\python\imgClassify\womanDir', 0, r'G:\xampp\htdocs\my\python\imgClassify\manWoman.csv')
    writeSum = 0
    for maindir, subdir, file_name_list in os.walk(imgDir):
        # print("1:",maindir) #当前主目录
        # print("2:",subdir) #当前主目录下的所有目录
        # print("3:",file_name_list)  #当前主目录下的所有文件
        for nowFile in file_name_list:
            if filterFileFun(nowFile, *deType):
                writeSum = writeSum + 1
                nowFile = maindir + "\\" + nowFile
                printMy("写入:" + nowFile)
                wImgToCsv(nowFile, tag, toCsv, output_shape=output_shape)
    printMy(("写入的总个数:", writeSum))


def wImgToCsv(imgUrl, tag, toCsv, output_shape=(100, 100)):
    """图片写入到csv

    :param imgUrl:
    :param tag:
    :param toCsv:
    :param output_shape: 压缩到的图片大小
    :return:

    """
    newDst = imgToNpArray(imgUrl, output_shape)
    newDstStr = str(tag) + "," + ",".join((str(x) for x in newDst)) + "\n"
    wFile(toCsv, newDstStr)
    # plt.imshow(dst)
    # plt.imshow(img)
    # plt.show()


def imgToNpArray(imgUrl, output_shape=(100, 100)):
    """读取图片

    :param imgUrl:
    :param tag:
    :param toCsv:
    :param output_shape: 压缩到的图片大小
    :return:

    """
    img = io.imread(imgUrl)
    dst = transform.resize(img, output_shape)
    print(dst.shape)
    newDst = dst.flatten()
    return newDst
